//1.引入相关模块
import  http =require( "http")
import  url=require("url")
import {HandleList} from "./handleList"
import {loadHandles}from "./loadHandles"


function StartServer():void
{
    var server =http.createServer(onHttp );
    server.listen(8080,()=>
    {
        loadHandles();//
    });
}
//var tt =new Handle_Test1();

function onHttp( req: http.IncomingMessage, res: http.ServerResponse):void
{
    var urlstr:string = "";

    if(req.url!=null)
    {
        urlstr = req.url;
    }
    //req是请求 
    var _url:url.UrlWithParsedQuery = url.parse(urlstr,true);
    if(_url.pathname!=null)
    {//找到其它的处理器
        var handleobj = HandleList.GetHandle(_url.pathname);
        if(handleobj!=null)
        {
            try
            {
                var bPost =req.method=="POST";
                if(bPost)
                    handleobj.onPost(req,res);
                else
                    handleobj.onGet(_url.query,res);
            }
            catch(err)
            {
                let errstr:string;
                if(err instanceof Error)
                {
                    errstr =(err as Error).message;
                }
                else
                {
                    errstr = JSON.stringify(err);
                }
                res.writeHead(200, {'Content-Type': 'text/html'});
                res.write('error in handle:'+   _url.pathname +"  "+JSON.stringify( _url.query) +"  Error"+errstr);
                res.end();
            }
            finally
            {
                return;
            }
        }
    }
    //找不到就走这条路
    //_url.pathname是请求的相对路径，可以根据这个分配给不同的http请求
    //req.method req.method is get or post
    
    res.writeHead(200, {'Content-Type': 'text/html'});
    var bPost =req.method=="POST";
    res.write('Hello Http Server:'+   _url.pathname +"  "+bPost +"  "+JSON.stringify( _url.query));
    res.end();
}

StartServer();